import {PlusOutlined} from '@ant-design/icons';
import {Button, Divider, message, Input, Drawer, Badge , Select, Form, Modal, Tag, DatePicker} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import ProcessHistoryForm from './components/ProcessHistoryForm';
import {queryOrder, engWorkOrder, proApprovalOrder} from "@/services/order";
import {queryProcessFlow} from "@/services/product";
import moment from "moment";




const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [formType, setFormType] = useState(1) // 1:新增 2:更新 3：详情
  const [activekey, setActiveKey] = useState('tab1');
  const [productData, setProductData] = useState({
    processData: [],
    customerData: []
  })
  const actionRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRow, setSelectedRow] = useState({});
  const { Option } = Select;
  const { RangePicker } = DatePicker;
  const handleApprovalModalVisible = (record)=>{
    formRef.setFieldsValue({
      ...record
    })
    setSelectedRow(record)
    handleModalVisible(true)
    setFormType(2)
  }

  const handleDetailModalVisible = (record)=>{
    formRef.setFieldsValue({
      ...record
    })
    setSelectedRow(record)
    handleModalVisible(true)
    setFormType(3)
  }

  const handleApproval = async (fields) => {
    fields.orderId = selectedRow.orderId;
    const hide = message.loading('正在提交');

    try {
      await engWorkOrder({...fields}).then(res=>{
        if(res && res.status === '0') {
          handleModalVisible(false)
          message.success('工程资料提交成功');
        }else {
          message.error(res.message);
        }
      });
      hide();
      return true;
    } catch (error) {
      hide();
      message.error('工程资料提交重试！');
      return false;
    }
  };


  const onSubmit = (orderDatas)=>{
    const success = handleApproval(orderDatas);
    if (success && actionRef.current) {
      actionRef.current.reload();
    }
  }

  const getProcessFlowData = async () => {
    try {
      await queryProcessFlow({
        pageNum: 1,
        pageSize: 9999,
        hidden: 0
      }).then(res => {
        if (res && res.status === '0') {
          const data = productData;
          data.processData = res.result.records;
          setProductData(data)
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      });
    } catch (error) {
      //console.log((error)
    }
  };

  useEffect(() => {
    const success = getProcessFlowData();
  }, [])

  const noApprovalColumns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      width: 80,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '订单编号',
      dataIndex: 'orderCode',
      width: 150,
      tip: '订单编号是唯一的',
      hideInForm: true,
      copyable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input placeholder={'请输入订单编号'}/>;
      }
    },
    // {
    //   title: '产品名称',
    //   dataIndex: 'productName',
    //   hideInSearch: true,
    //   width: 150,
    //   formItemProps: {
    //     rules: [
    //       {
    //         max: 10,
    //         message: '产品名称最大长度为10'
    //       },
    //       {
    //         whitespace: true,
    //         message: '请不要输入空格'
    //       }
    //     ],
    //   },
    //   valueType: 'input',
    //   renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
    //     return <Input maxLength={11} {...fieldProps} placeholder={'请输入产品名称'}/>;
    //   }
    // },
    {
      title: '产品编码',
      dataIndex: 'productCode',
      hideInSearch: true,
      width: 150,
    },
    {
      title: '生产编号',
      dataIndex: 'productionNo',
      width: 150,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={11} placeholder={'请输入生产编号'}/>;
      }
    },
    {
      title: '客户名称',
      dataIndex: 'custName',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '客户型号',
      dataIndex: 'clientCode',
      width: 150,
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '订货量(PCS)',
      width: 150,
      dataIndex: 'orderNum',
      hideInSearch: true
    },
    {
      title: '订单创建人',
      dataIndex: 'realName',
      width: 150,
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 200,
      sorter: true,
      valueType: 'dateTime',
      hideInForm: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <RangePicker />
        );
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => handleDetailModalVisible(record)}>
          详情
        </a>,
      ],
    },
  ];
  const tableRef = useRef();
  useEffect(() => {
    tableRef.current?.setFieldsValue({
      createTime: [moment().subtract(6, "days"), moment()],
    });
    tableRef.current?.submit();
  });
  return (
    <PageContainer>
      <ProTable
        style={{display: createModalVisible? 'none': 'block'}}
        actionRef={actionRef}
        formRef={tableRef}
        rowKey="orderId"
        search={{
          labelWidth: 120,
        }}
        request={async (params, sorter, filter) => {
          console.log(params)
          const param = params.createTime && params.createTime.length === 2 ?{
            ...params,
            pageNum: params.current,
            startDate: moment(params.createTime[0]).format("YYYY-MM-DD") + ' 00:00:00',
            endDate: moment(params.createTime[1]).format("YYYY-MM-DD") + ' 23:59:59',
            orderStatusMin: 9 // 查询投产中的订单
          }: {
            ...params,
            pageNum: params.current,
            orderStatusMin: 9 // 查询投产中的订单
          };
          const res = await queryOrder(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={noApprovalColumns}
      />
      {
        createModalVisible? <ProcessHistoryForm
          onCancel={() => handleModalVisible(false)}
          visible={createModalVisible}
          onSubmit={(orderData)=>onSubmit(orderData)}
          formType={formType}
          oldOrderData={selectedRow}
          baseData={productData}
        >
        </ProcessHistoryForm>: <></>
      }
    </PageContainer>
  );
};

export default TableList;
